#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>

void* start_send(void* arg)
{
	puts("***欢迎来到Gg聊天室***");
	printf("请输入你的聊天名：");
	char name[20] = {};
	gets(name);

	int sockfd = *(int*)arg;
	char buf[1024] = {};
	char buf1[1024] = {};
	for(;;)
	{
		gets(buf);
		sprintf(buf1, "%s:%s", name, buf);
		write(sockfd,buf1,strlen(buf1)+1);
		if(0 == strcmp("quit",buf))
		{
			printf("***退出聊天室***\n");
			pthread_exit(NULL);
		}
	}
}

void* start_recv(void* arg)
{
	int sockfd = *(int*)arg;
	char buf[1024] = {};
	for(;;)
	{
		read(sockfd,buf,sizeof(buf));
		printf("%s\n",buf);
	}
}

int main()
{
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > sockfd)
	{
		perror("socket");
		return -1;
	}

	struct sockaddr_in addr = {};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(7767);
	addr.sin_addr.s_addr = inet_addr("114.55.253.104");
	socklen_t len = sizeof(addr);

	if(connect(sockfd,(struct sockaddr*)&addr,len))
	{
		perror("bind");
		return -1;
	}

	pthread_t pid1;
	pthread_create(&pid1, NULL, start_recv, &sockfd);
	pthread_create(&pid1, NULL, start_send, &sockfd);		
	void* p = NULL;
	pthread_join(pid1, &p);
}
